import request from "./request";
import { requestWithAuth } from "./request";
import { ElMessage } from "element-plus";
import cache from "@/utils/cache";

// 缓存相关常量
const CACHE_KEY = {
  GOODS_LIST: "goods_list",
  GOOD_DETAIL: "good_detail_",
  CATEGORIES: "categories",
  COMMENTS: "comments_",
};

const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

/**
 * 统一的错误处理
 */
const handleError = (error, customMessage = "操作失败") => {
  console.error(error);
  ElMessage.error(customMessage);
  throw error;
};

// =============== 核心 CRUD 接口 ===============

/**
 * 获取商品列表
 */
export async function getGoods(params = {}) {
  try {
    const defaultParams = {
      pageSize: 10,
      pageIndex: 1,
      categoryId: undefined,
      keyword: "",
    };
    const queryParams = { ...defaultParams, ...params };
    
    const cacheKey = `${CACHE_KEY.GOODS_LIST}_${JSON.stringify(queryParams)}`;
    const cachedData = cache.get(cacheKey);
    
    if (cachedData) {
      return cachedData;
    }

    const response = await request({
      url: "/Good/list",
      method: "get",
      params: queryParams,
    });
    
    cache.set(cacheKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取商品列表失败");
  }
}

/**
 * 获取商品详情
 */
export async function getGoodDetail(spuId) {
  try {
    if (!spuId) throw new Error("商品ID不能为空");

    const cacheKey = `${CACHE_KEY.GOOD_DETAIL}${spuId}`;
    const cachedData = cache.get(cacheKey);
    if (cachedData) {
      return cachedData;
    }

    const response = await request({
      url: `/Good/detail/${spuId}`,
      method: "get",
    });
    
    cache.set(cacheKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取商品详情失败");
  }
}

/**
 * 创建商品
 */
export async function createGood(data) {
  try {
    if (!data) throw new Error("商品数据不能为空");
    
    const response = await requestWithAuth({
      url: "/Good/create",
      method: "post",
      data
    });
    
    cache.remove(CACHE_KEY.GOODS_LIST);
    return response;
  } catch (error) {
    handleError(error, "创建商品失败");
  }
}

/**
 * 更新商品
 */
export async function updateGood(spuId, data) {
  try {
    if (!spuId) throw new Error("商品ID不能为空");
    if (!data) throw new Error("更新数据不能为空");
    
    const response = await requestWithAuth({
      url: `/Good/update/${spuId}`,
      method: "put",
      data
    });
    
    cache.remove(`${CACHE_KEY.GOOD_DETAIL}${spuId}`);
    cache.remove(CACHE_KEY.GOODS_LIST);
    return response;
  } catch (error) {
    handleError(error, "更新商品失败");
  }
}

/**
 * 删除商品
 */
export async function deleteGood(spuId) {
  try {
    if (!spuId) throw new Error("商品ID不能为空");
    
    const response = await requestWithAuth({
      url: `/Good/delete/${spuId}`,
      method: "delete"
    });
    
    cache.clear();
    return response;
  } catch (error) {
    handleError(error, "删除商品失败");
  }
}

// =============== 其他接口 ===============

/**
 * 获取商品分类列表
 */
export async function getCategories() {
  try {
    const cachedData = cache.get(CACHE_KEY.CATEGORIES);
    if (cachedData) {
      return cachedData;
    }

    const response = await request({
      url: "/Good/categories",
      method: "get",
    });

    cache.set(CACHE_KEY.CATEGORIES, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取商品分类失败");
  }
}

/**
 * 获取商品评论
 */
export async function getGoodComments(spuId, params = {}) {
  try {
    if (!spuId) throw new Error("商品ID不能为空");

    const defaultParams = {
      pageSize: 10,
      pageIndex: 1,
    };
    const queryParams = { ...defaultParams, ...params };

    const cacheKey = `${CACHE_KEY.COMMENTS}${spuId}_${JSON.stringify(queryParams)}`;
    const cachedData = cache.get(cacheKey);
    if (cachedData) {
      return cachedData;
    }

    const response = await request({
      url: `/Good/comments/list/${spuId}`,
      method: "get",
      params: queryParams,
    });

    cache.set(cacheKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取商品评论失败");
  }
}
